﻿using Abp.Web.Models;
using AbpProjectTemplate.Web.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Threading.Tasks;
using AbpProjectTemplate.Web.Extensions;
using Polly;

namespace AbpProjectTemplate.Web.Controllers
{
    public class UploadController : AppApiControllerBase
    {
        const string _folder = "temp";
        const string _allowExtensions = ".jpg|.jpeg|.gif|.png|.bmp";
        private readonly IWebHostEnvironment _env;
        public UploadController(IWebHostEnvironment environment)
        {
            this._env = environment;
        }
        /// <summary>
        /// 文件上传
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> Post([FromForm] UploadInput input)
        {
            var lockerKey = this.AbpSession.UserId.HasValue ? $"upload{this.AbpSession.UserId}" : "upload";
            using (await this.SemaphoreSlimManager.LineUpAsync(lockerKey))
            {

                var fileExt = Path.GetExtension(input.File.FileName).ToLower();
                if (!_allowExtensions.Contains(fileExt))
                    throw new AppUserFriendlyException($"不支持的文件格式：{fileExt}！");

                var rnd = new Random(Guid.NewGuid().GetHashCode()).Next(1000, 9999);
                var fileName = input.FileName ?? $"{DateTime.Now.ToString("MMddHHmmss")}{rnd}{fileExt}";
                var folderPath = Path.Combine(this._env.WebRootPath, AppConsts.UploadFolder, _folder);
                if (!Directory.Exists(folderPath))
                    Directory.CreateDirectory(folderPath);
                var filePath = Path.Combine(folderPath, fileName);
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await input.File.CopyToAsync(stream);
                }
                //await Task.Delay(2000);
                var absoluteUrl = this.HttpContext.GetAbsoluteUri($"/{AppConsts.UploadFolder}/{_folder}/{fileName}");
                return this.Json(new { fileUrl = absoluteUrl });
            }
        }

        //[Route("/image/{name}")]
        //[HttpGet,DontWrapResult]
        //public async Task<ActionResult> GetFile(string name)
        //{
        //    var filePath = Path.Combine(this._env.WebRootPath, "Uploads", name);
        //    var ms = await Policy.Handle<IOException>()
        //        .WaitAndRetryAsync(5, retryCount => TimeSpan.FromSeconds(retryCount))
        //        .ExecuteAsync(async () =>
        //        {
        //            using (var fileStream = System.IO.File.OpenRead(filePath))
        //            {
        //                var memoryStream = new MemoryStream();
        //                await fileStream.CopyToAsync(memoryStream);
        //                return memoryStream;
        //            }
        //        });
        //    ms.Position = 0;
        //    return File(ms, "image/jpeg");
        //}
    }
}
